package com.logic.landseaserver.service.impl;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.config.ReportPenaltyPDFConfiguration;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.domain.ReportPenalty;
import com.logic.landseaserver.persistence.read.ReportPenaltyReadMapper;
import com.logic.landseaserver.persistence.write.ReportPenaltyWriteMapper;
import com.logic.landseaserver.service.IReportPenaltyService;
import com.logic.landseaserver.ws.dto.ReportPenaltyDTO;
import com.logic.landseaserver.ws.dto.ReportPenaltyPdfDTO;
import com.logic.system.domain.SystemFile;
import com.logic.system.persistence.write.FileWriteMapper;


@Service
public class ReportPenaltyServiceImpl implements IReportPenaltyService{

	private static final Logger log = LoggerFactory.getLogger(ReportPenaltyServiceImpl.class);

	@Autowired
	private ReportPenaltyReadMapper reportPenaltyReadMapper;

	@Autowired
	private ReportPenaltyWriteMapper reportPenaltyWriteMapper;

	@Autowired
	private ReportPenaltyPDFConfiguration reportPenaltyPDFConfiguration;

	@Autowired
	private FileWriteMapper fileWriteMapper;

	@Override
	public List<ReportPenaltyDTO> queryReportPenalty(Integer id) {
		//查出所有联系单
		List<ReportPenaltyDTO> reportPenaltyDTOs = new ArrayList<ReportPenaltyDTO>();

		List<ReportPenalty> reportPenaltys = new ArrayList<ReportPenalty>();
		reportPenaltys = reportPenaltyReadMapper.queryReportPenalty(id);
		Set<String> set = new HashSet<>();
		for (ReportPenalty reportPenalty : reportPenaltys) {
			Date date = reportPenalty.getPenaltyDtm();
			DateUtil dateUtil = new DateUtil();
			String   totalTime  = dateUtil.convertMonth(date);
			set.add(totalTime);
		}
		for (String totalTime : set) {
			ReportPenaltyDTO reportPenaltyDTO = new ReportPenaltyDTO();
			reportPenaltyDTO.setTotalTime(totalTime);
			List<ReportPenalty> monthReportPenaltys = new ArrayList<ReportPenalty>();
			for (ReportPenalty reportPenalty : reportPenaltys) {
				Date date = reportPenalty.getPenaltyDtm();
				DateUtil dateUtil = new DateUtil();
				String   totalTime1  = dateUtil.convertMonth(date);
				if (totalTime.equals(totalTime1)) {
					monthReportPenaltys.add(reportPenalty);
				}
			}
			reportPenaltyDTO.setMonthReportPenalty(monthReportPenaltys);
			reportPenaltyDTOs.add(reportPenaltyDTO);
		}

		return reportPenaltyDTOs;
	}

	@Override
	public void delete(String arg0) throws BusinessException {
		String[] idArr = arg0.split(",");
		for (String id : idArr) {
			Integer reportPenaltyId = Integer.valueOf(id);
			ReportPenalty reportPenalty = (ReportPenalty) this.getObject(reportPenaltyId);
			Boolean pass = this.validateForDelete(reportPenalty);
			if (pass) {
				reportPenalty.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
				reportPenaltyWriteMapper.deleteByPrimaryKey(reportPenalty);
			}
		}
	}



	@Override
	public Object get(Integer arg0) throws BusinessException {
		//return reportContactReadMapper.selectByPrimaryKey(arg0);
		return null;
	}

	public Object getObject(Integer arg0) throws BusinessException {
		return reportPenaltyReadMapper.selectByPrimaryKey(arg0);

	}

	@Override
	public int insert(Object arg0) throws BusinessException {
		Integer id = -1;
		Boolean pass = this.validateForInsert(arg0);
		if (pass) {
			ReportPenalty reportPenalty = (ReportPenalty)arg0;
			reportPenalty.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
			id = reportPenaltyWriteMapper.insertSelective(reportPenalty);

		}
		return id;
	}

	public static void fillData(AcroFields fields, Map<String, String> data)
			throws IOException, DocumentException
	{
		for (String key : data.keySet())
		{
			String value = data.get(key);
			fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
		}
	}

	@Override
	public List<?> query(QueryUtil arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update(Object arg0) throws BusinessException {


	}

	@Override
	public Boolean validate(Object arg0) throws BusinessException {
		Boolean pass = true;
		return pass;
	}

	@Override
	public Boolean validateForDelete(Object arg0) throws BusinessException {
		return true;
	}

	@Override
	public Boolean validateForInsert(Object arg0) throws BusinessException {
		Boolean pass = false;
		pass = this.validate(arg0);
		return pass;
	}

	@Override
	public Boolean validateForUpdate(Object arg0) throws BusinessException {
		Boolean pass = false;
		pass = this.validate(arg0);
		return pass;	}

	@Override
	public ReportPenaltyPdfDTO getPdfDitail(Integer id) {
		ReportPenaltyPdfDTO dto = reportPenaltyReadMapper.getReportPenaltyPdfDTO(id);
		return dto;
	}

	@Override
	public String  reportPenaltyPdf(ReportPenaltyPdfDTO dto) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		data.put("id", dto.getId()== null ? "" : dto.getId().toString());
		data.put("name", dto.getName()== null ? "" : dto.getName().toString());
		data.put("time", dto.getTime()== null ? "" : dto.getTime().toString());
		data.put("contractorUnit", dto.getContractorUnit()== null ? "" : dto.getContractorUnit().toString());
		data.put("relatedPeople", dto.getRelatedPeople()== null ? "" : dto.getRelatedPeople().toString());
		data.put("punishReason", dto.getPunishReason()== null ? "" : dto.getPunishReason().toString());
		data.put("rectificateRequire", dto.getRectificateRequire()== null ? "" : dto.getRectificateRequire().toString());
		data.put("penaltyDecision", dto.getPenaltyDecision()== null ? "" : dto.getPenaltyDecision().toString());
		data.put("projectManager", dto.getProjectManager() == null ? "" : dto.getProjectManager().toString());
		data.put("examiner", dto.getExaminer() == null ? "" : dto.getExaminer().toString());
		data.put("receiverPunishPeople", dto.getReceiverPunishPeople() == null ? "" : dto.getReceiverPunishPeople().toString());
		String result = producePDF(data,dto);
		return result;
	}

	public String  producePDF(Map<String, String> data, ReportPenaltyPdfDTO dto)throws Exception{
		OutputStream fos = null;
		ByteArrayOutputStream bos = null;
		Integer fileId = null;
		String localPath = null;
		try {
			PdfReader reader = new PdfReader(ReportPenaltyServiceImpl.class.getClassLoader().getResource("reportPenaltyPdf.pdf"));
			bos = new ByteArrayOutputStream();
			/* 将要生成的目标PDF文件名称 */
			PdfStamper ps = new PdfStamper(reader, bos);
			PdfContentByte under = ps.getUnderContent(7);
			/* 使用中文字体 */
			BaseFont bf =
					BaseFont.createFont(ContractServiceImpl.class.getClassLoader().getResource("STSONG.TTF").toString(),
							BaseFont.IDENTITY_H,
							BaseFont.NOT_EMBEDDED);
			Font font = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD);
			ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
			fontList.add(bf);
			/* 取出报表模板中的所有字段 */
			AcroFields fields = ps.getAcroFields();
			fields.setSubstitutionFonts(fontList);
			fillData(fields, data);

			ps.setFormFlattening(true);
			ps.close();
			String filePath = reportPenaltyPDFConfiguration.getLocal()+"/"+reportPenaltyPDFConfiguration.getReportPenaltyPath();
			File file = new File(filePath);
			//如果文件不存在则创建
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			Date nowTime = new Date(System.currentTimeMillis());
			SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
			String time = sdFormatter.format(nowTime);
			// String filename = filepath + "/" + data.get("depositSN") + "_" + time + ".pdf";
			String fileName = filePath + "/" + data.get("id") + "_" + time + ".pdf";
			fos = new FileOutputStream(fileName);
			fos.write(bos.toByteArray());

			// 将url插入数据库
			SystemFile systemFile = new SystemFile();
			String fileName1 = data.get("id") + "_" + time + ".pdf";
			int size = bos.size() / 1024;
			systemFile.setFileSize(size);
			systemFile.setPath(reportPenaltyPDFConfiguration.getReportPenaltyPath());
			systemFile.setFileType("pdf");
			systemFile.setName(fileName1);
			systemFile.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
			localPath =
					reportPenaltyPDFConfiguration.getRemote() + "/" + reportPenaltyPDFConfiguration.getReportPenaltyPath() + "/" + fileName1;

			fileWriteMapper.insertSelective(systemFile);
			fileId = systemFile.getId();
			
			savePath(dto,fileId);

		} catch (Exception e) {
			log.info("producePDF Exception:"+e);
			throw e;
		}finally
		{
			fos.flush();
			fos.close();
			bos.close();
		}
		return localPath;
	}
		public void savePath(ReportPenaltyPdfDTO dto,Integer fileId){
			ReportPenalty reportPenalty= new ReportPenalty();
            if (fileId != null)
            {
            	String pdfPath = fileId.toString();
            	reportPenalty.setPdfPath(pdfPath);;
            }
            reportPenalty.setId(dto.getId());
            reportPenalty.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            reportPenaltyWriteMapper.updateByPrimaryKeySelective(reportPenalty);
		}
}
